<template>
  <div class="TaskReview">
    <BigImg
      :visible="photoVisible"
      :url="bigImgUrl"
      @closeClick="
        () => {
          photoVisible = false;
        }
      "
    ></BigImg>
    <!-- 左侧 -->
    <a-row style="width: 100%; height: 100%">
      <a-col :md="leftColMd" style="background: #fff; padding: 10px; height: 100%">
        <div class="TaskReview_left">
          <div class="TaskReview_left_top">
            <div class="TaskReview_left_top_name">
              <div class="icon_box">
                <i class="iconfont icon-yueyongdianliangbili"></i>
              </div>

              <div class="name">核算数据审核</div>
            </div>
            <!-- <div class="TaskReview_left_top_btn">
          <i class="iconfont icon-xinjianchuangkou" style="font-size:22px"></i>
            </div>-->
          </div>
          <div class="TaskReview_left_center">
            <div>1 个项目 • 已在6 分钟前更新</div>
            <div>
              <i class="iconfont icon-gonggeshitu" style="font-size: 22px"></i>
              <i class="iconfont icon-shuaxin1" style="font-size: 22px"></i>
            </div>
          </div>
        <a-form @keyup.enter.native="searchQuery">
            <a-form-item>
              <a-input-search placeholder="搜索任务" v-model="queryParam.taskName"  @search="searchQuery" />
            </a-form-item>
          </a-form>
          <div class="TaskReview_left_list">
              <a-table
                class="table_overflow scrollbar"
                ref="table"
                size="middle"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                :loading="loading"
                @change="handleTableChange"
              >
                <span slot="action" slot-scope="text, record">
                  <a-button @click="queryFacilitiesListFun(record)">审核</a-button>
                </span>
              </a-table>
          </div>
        </div>
      </a-col>
      <!-- 右侧 -->
      <a-col :md="rightColMd" style="height: 100%; padding: 0 0 0 10px">
        <div
          class="TaskReview_right scrollbar"
          style="background: #fff; height: 100%"
          v-if="taskInfo"
        >
          <!-- 右上 -->
          <div class="TaskReview_right_top">
            <div class="TaskReview_right_top_header">
              <div class="TaskReview_right_top_header_box">
                <div class="icon_box">
                  <i class="iconfont icon-yueyongdianliangbili"></i>
                </div>
                <div class="TaskReview_right_top_header_box_name" v-if="taskInfo">
                  <div class="left_con">
                    <div class="name_val">{{ taskInfo.taskName }}</div>
                    <div
                      class="name"
                      style="font-size:12px:min-height:20px"
                    >{{ taskInfo.description }}</div>
                  </div>

                  <div class="right_con">
                    <a-button
                      style="border-radius: 0"
                      class="_private_btn"
                      type="primary"
                      @click="allUrge"
                    >一键催填</a-button>
                  </div>
                </div>
              </div>
            </div>
            <div class="TaskReview_right_top_other">
              <div class="name">审核进度:</div>
              <!---->
              <a-progress :percent="percentage" />
            </div>
          </div>
          <!-- 右下 -->
          <div class="TaskReview_right_bottom">
            <a-tabs default-active-key="1">
              <a-tab-pane key="1">
                <span slot="tab" class="title">
                  <i class="iconfont icon-bg-info"></i>
                  <div>详细信息</div>
                </span>
                <div class="info_box">
                  <a-collapse v-model="activeKey">
                    <a-collapse-panel
                      v-for="(item, index) in facilitiesListSource"
                      :key="String(index)"
                    >
                      <template slot="header">
                        <div class="header">
                          <div>{{ item[0].title }}</div>
                          <div class="right_num">
                            已填报: {{ fillComputed(item) }} &nbsp; 审核通过:{{
                            auditComputed(item)
                            }}
                          </div>
                          <!-- <div class="right_num">当前审核:{{headerComputed()}}</div> -->
                        </div>
                      </template>
                      <div class="info">
                        <div v-for="(k, v) in item" :key="v" style="margin-bottom: 16px">
                          <div class="info_header">
                            <div class="name" :style="{ color: k.background }">
                              <i :class="k.iconfont" class="iconfont"></i>
                              {{ k.categoryName }} {{ facilityComputed(k) }}
                            </div>
                            <div
                              v-if="
                                selectedRowKeysComputed(k.facilityList).length >
                                0
                              "
                            >
                              <a-button
                                style="border-radius: 0"
                                class="_private_btn"
                                type="primary"
                                @click="
                                  batchFun(
                                    selectedRowKeysComputed(k.facilityList),
                                    1
                                  )
                                "
                              >通过</a-button>
                              <a-button
                                style="border-radius: 0"
                                class="_private_btn"
                                type="primary"
                                @click="
                                  batchFun(
                                    selectedRowKeysComputed(k.facilityList),
                                    2
                                  )
                                "
                              >拒绝</a-button>
                            </div>
                          </div>

                          <!--       rowKey="id" -->
                          <a-table
                            class="table_overflow scrollbar"
                            ref="table"
                            size="middle"
                            bordered
                            :rowKey="(row) => row.fillingId"
                            :columns="columns1"
                            :pagination="false"
                            :dataSource="k.facilityList"
                            :loading="loading"
                            :rowSelection="{
                              selectedRowKeys: selectedRowKeys,
                              onChange: onSelectChange,
                            }"
                          >
                            <span slot="fillingStatus" slot-scope="text, record">
                              {{
                              record.fillingStatus == 2 ? "完成" : "未填报"
                              }}
                            </span>
                            <span
                              slot="voucher"
                              slot-scope="text, record"
                            >{{ record.voucher == 2 ? "无" : "" }}</span>
                            <span slot="action" slot-scope="text, record">
                              <div v-if="record.fillingStatus == 2">
                                <div v-if="record.approveStatus == 0">
                                  <a-button @click="audit(record, 1)">通过</a-button>
                                  <a-button @click="audit(record, 2)">拒绝</a-button>
                                </div>
                                <div v-if="record.approveStatus == 1">已通过</div>
                              </div>
                              <div v-else>
                                <a-button @click="urgeFun(record)">催填</a-button>
                              </div>
                            </span>
                          </a-table>
                        </div>
                      </div>
                    </a-collapse-panel>
                  </a-collapse>
                </div>
              </a-tab-pane>
              <a-tab-pane key="2">
                <span slot="tab" class="title">
                  <i class="iconfont icon-guanlian2"></i>
                  <div>相关</div>
                </span>

                <a-list
                  :grid="{ gutter: 16, column: 4 }"
                  :data-source="data"
                  style="margin-top: 6px"
                >
                  <a-list-item slot="renderItem" slot-scope="item, index">
                    <a-card :title="item.title">
                      <div style="width: 100%; margin-bottom: 6px; cursor: pointer">
                        <img
                          @click.self="showBigImage($event)"
                          style="width: 100%; border-radius: 5px"
                          src="@/assets/img/fujin1.jpg"
                          alt
                        />
                      </div>
                      <a-button>退回</a-button>
                      <a-button>删除</a-button>
                    </a-card>
                  </a-list-item>
                </a-list>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import BigImg from "@/components/Tools/BigImg.vue";
import JUserSelectDepart from "@/components/Control/JUserSelectDepart.vue";
import {
  queryDepartAuditList,
  queryUserDepartList,
  queryTaskBoundaryList,
  emissionSourceAudit,
  urge,
  batchEmissionSourceAudit
} from "@/api/api";
import { ListMixin } from "@/mixins/ListMixin";
import { mapActions, mapGetters, mapState } from "vuex";
export default {
  mixins: [ListMixin],
  data() {
    return {
      photoVisible: false,
      bigImgUrl: "",
      taskListData: [],
      facilitiesListSource: null,
      taskInfo: null,
      informantUserIds: [],

      facilitiesList: [],
      sourceList: [
        {
          titlt: "范围一 : 直接排放",
          key: "scope1",
          background: "rgba(252, 220, 208, 1),rgba(253, 243, 242, .3)"
        },
        {
          titlt: "范围二 : 间接排放",
          key: "scope2",
          background: "rgba(254, 240, 223, 1),rgba(254, 240, 223, 1)"
        },
        {
          titlt: "范围三 : 价值链排放",
          key: "scope3",
          background: "rgba(232, 233, 251, 1),rgba(232, 233, 251, .3)"
        }
      ],
      loading: false,
      selectedRowKeys: [],
      selectionRows: [],
      activeKey: ["0", "1", "2"],
      data: [
        {
          title: "附件1"
        },
        {
          title: "附件2"
        },
        {
          title: "附件3"
        },
        {
          title: "附件4"
        }
      ],
      url: {
        list: "/accounting/audit/list"
      },
      columns1: [
        {
          title: "设施名称",
          align: "facilitiesName",
          dataIndex: "facilitiesName"
        },
        {
          title: "排放源",
          align: "boundaryName",
          dataIndex: "boundaryName"
        },
        {
          title: "填报人",
          align: "informant",
          dataIndex: "informant"
        },
        {
          title: "填报状态",
          align: "fillingStatus",
          dataIndex: "fillingStatus",
          scopedSlots: { customRender: "fillingStatus" }
        },
        {
          title: "核算结果",
          align: "emission",
          dataIndex: "emission"
        },
        {
          title: "凭证",
          align: "voucher",
          dataIndex: "voucher",
          scopedSlots: { customRender: "voucher" }
        },

        {
          title: "操作",
          dataIndex: "action",
          align: "left",
          scopedSlots: { customRender: "action" }
        }
      ],

      columns: [
        {
          title: "任务名称",
          align: "left",
          dataIndex: "taskName"
        },
        {
          title: "进度",
          align: "left",
          dataIndex: "progress"
        },

        {
          title: "创建人 ",
          align: "left",
          dataIndex: "createBy"
        },

        {
          title: "操作",
          dataIndex: "action",
          align: "left",
          scopedSlots: { customRender: "action" }
        }
      ]
    };
  },
  components: {
    BigImg,
    JUserSelectDepart
  },
  mounted() {
    // let userId = this.userInfo().id;
    // let param = { userId: userId };
    // 如果拥有多部门,进行部门选择
    // queryUserDepartList(param).then((res) => {
    //   if (res.result.length > 1) {
    //     this.$refs.userSelectDepart.show(res.result);
    //   } else {
    //     this.queryDepartAuditListFun(res.result[0].value);
    //   }
    // });
  },
  computed: {
    leftColMd() {
      return !this.taskInfo ? 24 : 6;
    },
    rightColMd() {
      return !this.taskInfo ? 0 : 18;
    },
    percentage() {
      var total = 0;
      var finishNum = 0;
      if (this.facilitiesList)
        this.facilitiesList.forEach(item => {
          console.log(item);
          if (item.approveStatus == 1) {
            finishNum++;
          }
          total++;
        });
      console.log(finishNum, total);
      return Number(((finishNum / total) * 100).toFixed(2));
    },
    facilityComputed() {
      return function(scopeObj) {
        return scopeObj.facilityList.length;
      };
    },
    fillComputed() {
      return function(scopeObj) {
        var total = 0;
        var finishNum = 0;
        if (this.facilitiesList)
          scopeObj.forEach(item => {
            item.facilityList.forEach(facility => {
              if (facility.fillingStatus == 2) {
                finishNum++;
              }
              total++;
            });
          });
        return ` ${finishNum}/${total}`;
      };
    },
    auditComputed() {
      return function(scopeObj) {
        var total = 0;
        var finishNum = 0;

        scopeObj.forEach(item => {
          item.facilityList.forEach(facility => {
            if (facility.approveStatus == 1) {
              finishNum++;
            }
            total++;
          });
        });
        return ` ${finishNum}/${total}`;
      };
    },
    selectedRowKeysComputed() {
      var that = this;
      return function(facilityList) {
        var facilityFillingIdList = []; //类型下设施的id存储
        var selectFacilityFillingId = []; //对比存在的id列表
        // 找到该类型所有的id
        facilityList.forEach(item => {
          facilityFillingIdList.push(item.fillingId);
        });
        // 在所有的已选项进行过滤
        selectFacilityFillingId = facilityFillingIdList.filter(item => {
          return that.selectedRowKeys.includes(item);
        });
        return selectFacilityFillingId;
      };
    }
  },
  methods: {
    onSelectChange(selectedRowKeys, selectionRows) {
      console.log(selectedRowKeys, selectionRows);
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    // 批量操作函数 type1为通过  2为拒绝
    batchFun(data, type) {
      batchEmissionSourceAudit({
        ids: data.join(","),
        approveStatus: type
      }).then(res => {
        console.log(res);
        let param = {
          taskId: this.taskId
        };
        // 批量审核成功后清除已选项
        this.clearSelectFacilityFillingId(this.facilitiesList);
        this.queryFacilitiesList(param).then(res => {
          this.facilitiesList = res.result.fbList;
          this.taskInfo = res.result.task;

          // 数据分类
          this.TaskBoundaryClassification();
        });
      });
    },
   
    allUrge() {
      var informantUserIdsArr = [];
      this.facilitiesList.forEach(item => {
        this.informantUserIds = [];
        if (item.approveStatus == 0) {
          if (informantUserIdsArr.indexOf(item.informantUserId) == -1) {
            informantUserIdsArr.push(item.informantUserId);
          }
        }
      });
      this.informantUserIds = informantUserIdsArr;
      urge({
        task: this.taskInfo,
        informantUserIds: this.informantUserIds
      }).then(res => {
        if (res.success) {
          this.$message.success("已催填");
        }
      });
    },
    urgeFun(fillObj) {
      this.informantUserIds = [fillObj.informantUserId];
      urge({
        task: this.taskInfo,
        informantUserIds: this.informantUserIds
      }).then(res => {
        if (res.success) {
          this.$message.success("已催填");
        }
      });
    },
    audit(obj, val) {
      console.log(obj, val);
      let auditParam = {
        fillingId: obj.fillingId,
        approveStatus: val
      };
      emissionSourceAudit(auditParam).then(res => {
        console.log(res);
        let param = {
          taskId: this.taskId
        };
        this.queryFacilitiesList(param).then(res => {
          this.facilitiesList = res.result.fbList;
          this.taskInfo = res.result.task;

          // 数据分类
          this.TaskBoundaryClassification();
        });
      });
    },
    // 操作完成清除已选对象
    clearSelectFacilityFillingId(arr) {
      var facilityFillingIdList = []; //类型下设施的id存储
      arr.forEach(item => {
        facilityFillingIdList.push(item.fillingId);
      });
      this.selectedRowKeys = this.selectedRowKeys.filter(
        fillingId => !facilityFillingIdList.includes(fillingId)
      );
    },
    // 获取用户信息
    // ...mapGetters(["userInfo"]),
    // 选择部门
    // userSelectDepartFun() {
    //   this.$refs.userSelectDepart.visible = false;
    //   this.queryDepartAuditListFun(this.$refs.userSelectDepart.orgCode);
    // },
    // 根据部门获取任务列表
    // queryDepartAuditListFun(departId) {
    //   let param = { departId: departId };
    //   queryDepartAuditList(param).then((res) => {
    //     console.log(res);
    //     this.taskListData = res.result;
    //   });
    // },
    // 通过任务id获取设施列表事件
    queryFacilitiesListFun(taskName) {
      this.taskId = taskName.id;
      let param = {
        taskId: this.taskId
      };
      this.queryFacilitiesList(param);
    },
    // 获取设施列表函数
    queryFacilitiesList(param) {
      queryTaskBoundaryList(param).then(res => {
        console.log(res);
        this.facilitiesList = res.result.fbList;
        console.log(this.facilitiesList);
        this.taskInfo = res.result.task;
        // 数据分类
        this.TaskBoundaryClassification();
      });
    },
    TaskBoundaryClassification() {
      var dataSource = [];
      var scopeObj = {};
      var Category = {};
      this.facilitiesList.forEach(item => {
        if (!scopeObj["scope" + item.scopeCode]) {
          scopeObj["scope" + item.scopeCode] = [];
        }
        scopeObj["scope" + item.scopeCode].push(item);
      });
      // 第二层类别
      for (let key in scopeObj) {
        // console.log(scopeObj[key]);
        if (Array.isArray(scopeObj[key])) {
          scopeObj[key].forEach(Accounting => {
            if (!Category["Category" + Accounting.boundaryCategoryCode]) {
              Category["Category" + Accounting.boundaryCategoryCode] = {};
              if (Accounting.boundaryCategoryCode == 1) {
                Category["Category" + Accounting.boundaryCategoryCode][
                  "background"
                ] = "#f74b4a";
                Category["Category" + Accounting.boundaryCategoryCode][
                  "iconfont"
                ] = "icon-jianzhuanquan-";
              } else {
                Category["Category" + Accounting.boundaryCategoryCode][
                  "background"
                ] = "#f74b4a";
                Category["Category" + Accounting.boundaryCategoryCode][
                  "iconfont"
                ] = "icon-jianzhuanquan-";
              }
              Category["Category" + Accounting.boundaryCategoryCode][
                "scopeCode"
              ] = Accounting.scopeCode;
              Category["Category" + Accounting.boundaryCategoryCode]["title"] =
                Accounting.scopeName;
              Category["Category" + Accounting.boundaryCategoryCode][
                "categoryName"
              ] = Accounting.boundaryCategoryName;

              Category["Category" + Accounting.boundaryCategoryCode][
                "facilityList"
              ] = [];
              // Category["Category" + Accounting.boundaryCategoryCode][
              //   "selectionRows"
              // ] = ["1641741994545975297"];
            }
            Category["Category" + Accounting.boundaryCategoryCode][
              "facilityList"
            ].push(Accounting);
          });
        }
      }
      for (let key in Category) {
        console.log(dataSource);
        if (Category[key].scopeCode == "1") {
          if (!Array.isArray(dataSource[0])) {
            dataSource[0] = [];
          }
          dataSource[0].push(Category[key]);
        }
        if (Category[key].scopeCode == "2") {
          if (!Array.isArray(dataSource[1])) {
            dataSource[1] = [];
          }
          dataSource[1].push(Category[key]);
        }
        if (Category[key].scopeCode == "3") {
          if (!Array.isArray(dataSource[2])) {
            dataSource[2] = [];
          }
          dataSource[2].push(Category[key]);
        }
      }
      console.log(dataSource);
      this.facilitiesListSource = dataSource;
    },
    onClick() {},
    showBigImage(e) {
      //点击图片函数，点击后，把photoVisible设置成true
      if (e != "") {
        this.photoVisible = true;
        this.bigImgUrl = e.currentTarget.src;
      }
    },

    onSearch() {}
  }
};
</script>

<style lang="scss">
@import "@/assets/css/taskReview.scss";
@import "@/assets/css/scrollbar.scss";
</style>